import org.apache.log4j.Logger

// Represents a "master" image - a full size image as shot by the camera
// Master must have one or more versions, e.g. a thumbnail, display size,
// larger display size. 
class Master {

  static constraints = {
    checksum(maxSize:40, unique:true)
    fileName(maxSize:256, blank:false)
    relativePath(maxSize:512, blank:false)
    imageHeight(min:1) // Integer fields are strictly positive
    imageWidth(min:1)
    //fileSize(min:1) // There appears to be a bug in GORM due to which constraints on long fields fail
  }
  
  static mapping = {
    comment type:'text'
    versions lazy:false
    uploaded index:'Uploaded_IDX'
    isPublic index:'Public_IDX'
  }

  static hasMany = [versions:Version]

  String checksum
  String comment = ''
  Date created
  Date uploaded
  String fileName
  String relativePath
  int imageHeight
  int imageWidth
  long fileSize
  boolean isPublic

  private static final Logger slog = Logger.getLogger(GalleryController.class)

  static List<Master> getAllMastersWithTags(Tag... tags) {

    def tagIds = tags.findAll{ it != null }.collect{ it.id }
    if(tagIds.empty) {
      return []
    }

    // slog.error(tagIds)

    return Master.executeQuery("select distinct m from Master as m join fetch m.versions " +
         "where m.id in (select m.id from " +
         "Master as m, MasterTag as mt, Tag as t " +
         "where t.id in (:tagIds) and mt.masterId=m.id and mt.tagId=t.id " +
         "group by m.id having count(m. id) = :tagIdsLength order by m.id) " +
         "order by m.created",['tagIds':tagIds, 'tagIdsLength':tagIds.size() as long])
  }

  static List<Master> get50MostRecentPublicMasters() {
    return Master.executeQuery("select distinct m from Master as m join fetch m.versions " +
      "where m.public = true order by m.uploaded desc limit 50")
  }
}
